package com.example.service01.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Dict;
import com.example.service01.api.Service02Impl;
import com.framework.common.api.CommonResult;
import com.framework.common.auto.AuthConstant;
import com.framework.common.auto.TokenUserInfo;
import com.framework.common.auto.UserInfo;
import com.framework.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lihanbo
 */
@RestController
@Slf4j
public class Service01Controller {

    @Autowired
    private RedisUtils redisUtils;
    @Value("${sa-token.timeout:2592000}")
    private Integer tokenTimeout;
    @Autowired
    private Service02Impl service02;


    @PostMapping("/public/login")
    public CommonResult<?> login() {
        //模拟登陆后拿到用户token
        //数据库查询用户信息实体
        UserInfo userInfo = new UserInfo();
        userInfo.setId(10000L)
                .setUsername("admin")
                .setName("管理员");
        //设置用户接口权限
        List<String> permissions = new ArrayList<>();
        //这里权限标识可以编辑，网关中接口的权限对应即可; 星号为通配符
        permissions.add("api:service01:*");
        permissions.add("api:service02:*");

        //satoken 登陆方法 用户token会写入到 redis中,token有效时长自行配置
        StpUtil.login(userInfo.getId(), AuthConstant.ADMIN_CLIENT_ID);
        //获取satoken 提供的用户token
        String tokenValue = StpUtil.getTokenValue();
        TokenUserInfo tokenUserInfo = new TokenUserInfo()
                .setSubject(AuthConstant.ADMIN_CLIENT_ID)
                .setUserInfo(userInfo)
                .setPermissionList(permissions)
                .setToken(tokenValue);
        //将用户的token、基本信息、权限保存到redis中
        redisUtils.set(AuthConstant.LOGINID_PREFIX + userInfo.getId(), tokenUserInfo, tokenTimeout);
        return CommonResult.success(tokenUserInfo);
    }

    @SaCheckPermission("api:service01:test")
    @PostMapping("/test")
    public CommonResult<?> test() {
        return CommonResult.success(Dict.create().set("pro", "Service01"));
    }

    @SaCheckPermission("api:service01:Service02Test")
    @PostMapping("/Service02Test")
    public CommonResult<?> Service02Test() {
        return service02.test();
    }

}
